package svc

import (
	"gitee.com/gopher2011/go-zero-gva/internal/config"
	"gitee.com/gopher2011/go-zero-gva/internal/middleware"
	"github.com/tal-tech/go-zero/core/stores/cache"
	"github.com/tal-tech/go-zero/core/syncx"
	"github.com/tal-tech/go-zero/rest"
	"golang.org/x/sync/singleflight"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

type ServiceContext struct {
	Config          config.Config
	DB              *gorm.DB
	Cache           cache.Cache
	OperationRecord rest.Middleware
	JwtAuth         rest.Middleware
	CasbinHandler   rest.Middleware
	ConcurrencyControl *singleflight.Group
}

func NewServiceContext(c config.Config) *ServiceContext {
	conn, _ := gorm.Open(mysql.New(mysql.Config{
		DSN:               c.Database.DSN,
		DefaultStringSize: 171, //数据库varchar类型的默认值
	}), &gorm.Config{
		SkipDefaultTransaction: false, //启用事务
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "",   //表前缀
			SingularTable: true, //使用单数表名
		},
		DryRun:                                   false,                               //禁止SQL空跑
		DisableForeignKeyConstraintWhenMigrating: true,                                //创建逻辑外键
		Logger:                                   logger.Default.LogMode(logger.Info), //输出 SQL语句
	})
	return &ServiceContext{
		Config:          c,
		DB:              conn,
		Cache:           cache.New(c.CacheRedis, syncx.NewSingleFlight(), cache.NewStat(""), nil),
		OperationRecord: middleware.NewOperationRecord().Handle,
		JwtAuth:         middleware.NewJwtAuth().Handle,
		CasbinHandler:   middleware.NewCasbinHandler().Handle,
	}
}

func (it *ServiceContext) AutoMigrate() {
	it.DB.AutoMigrate(
		&SysUser{},
		&SysAuthority{},
		&SysApi{},
		&SysBaseMenu{},
		&SysBaseMenuParameter{},
		&JwtBlacklist{},
		&SysDictionary{},
		&SysDictionaryDetail{},
		&SysOperationRecord{},
		&SysAutoCodeHistory{},
		&ExaFileUploadAndDownload{},
		&ExaFile{},
		&ExaFileChunk{},
		&ExaSimpleUploader{},
		&ExaCustomer{},
		&AutoCodeExample{})
}
